
var TodoController = function($scope, $http){
	
	$http.defaults.headers.post["Content-Type"] = "application/json";
	var urlBase="http://localhost:8080/angularjs";
	
	$scope.editMode = false;
	$scope.id = '';
	
	$scope.getAllTodo = function(){
		$scope.resetError();
		$http.get(urlBase + '/todo/all.json').success(function(respone){
			$scope.todoUsers = respone;
		}).error(function(){
			$scope.setError("Couldn't not display all user");
		});
	}
	
	$scope.addTodo = function(name){
		$scope.resetError();
		$http.post(urlBase + '/todo/add/' + name).success(function(respone){
			$scope.getAllTodo();
		}).error(function(){
			$scope.setError("Couldn't add user");
		});
		$scope.todoName = '';
	}
	
	$scope.deleteTodo = function(id){
		$scope.resetError();
		$http.delete(urlBase + '/todo/delete/' + id).success(function(respone){
			$scope.getAllTodo();
		}).error(function(){
			$scope.setError("Couldn't delete user");
		});
	}
	
	$scope.editTodo = function(id){
		$scope.resetError();
		$http.post(urlBase + '/todo/edit/' + id).success(function(user){
			$scope.id = id;
			$scope.editMode = true;
			$scope.todoName = user.name;
		}).error(function(){
			$scope.setError("Couldn't edit");
		});
	}
	
	
	$scope.updateTodo = function(name){
		$scope.setError();
		$http.put(urlBase + '/todo/update/' + $scope.id + '/' + name).success(function(respone){
			$scope.getAllTodo();
			$scope.id = '';
			$scope.editMode = false;
		}).error(function(){
			$scope.setError("Couldn't update user");
		});
	}
	
	$scope.deleteAllTodo = function(){
		$scope.setError();
		$http.delete(urlBase + '/todo/deleteAll').success(function(respone){
			$scope.getAllTodo();
		}).error(function(){
			$scope.setError("Sorry. Can't delete All");
		});
	}
	
	$scope.resetTodoField = function(){
		$scope.resetError();
		$scope.todoName = '';
	}
	
	$scope.resetError = function(){
		$scope.error = false;
		$scope.messageError = '';
	}
	
	$scope.setError = function(message){
		$scope.error = true;
		$scope.errorMessage = message;
	}
	
	/*Always show table user when go todo layout*/
	$scope.getAllTodo();
	
}